#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
民法典数据库健康检查工具
"""

from pymongo import MongoClient
from datetime import datetime
import json
import time

def health_check():
    """执行数据库健康检查"""
    print("=" * 60)
    print("🏥 民法典数据库健康检查")
    print("=" * 60)
    
    health_report = {
        "check_time": datetime.now().isoformat(),
        "database": "civil_code_db",
        "status": "healthy",
        "issues": [],
        "statistics": {}
    }
    
    try:
        client = MongoClient("mongodb://localhost:27017/")
        db = client['civil_code_db']
        collection = db['civil_code_articles']
        
        # 1. 数据完整性检查
        print("📊 数据完整性检查:")
        total_count = collection.count_documents({})
        print(f"   总条文数: {total_count}")
        
        if total_count != 1260:
            health_report["issues"].append(f"数据不完整：期望1260条，实际{total_count}条")
            health_report["status"] = "warning"
        else:
            print("   ✅ 数据完整性正常")
        
        health_report["statistics"]["total_articles"] = total_count
        
        # 2. 索引状态检查
        print("\n🔍 索引状态检查:")
        indexes = list(collection.list_indexes())
        required_indexes = [
            "civil_code_text_search",
            "keywords_array_index", 
            "article_number_unique",
            "chapter_compound_index"
        ]
        
        existing_indexes = [idx.get('name', '') for idx in indexes]
        missing_indexes = [idx for idx in required_indexes if idx not in existing_indexes]
        
        if missing_indexes:
            health_report["issues"].append(f"缺失索引：{missing_indexes}")
            health_report["status"] = "error"
            print(f"   ❌ 缺失索引: {missing_indexes}")
        else:
            print("   ✅ 所有必需索引存在")
        
        health_report["statistics"]["indexes_count"] = len(indexes)
        
        # 3. 搜索功能检查
        print("\n🔍 搜索功能检查:")
        test_queries = ["民事", "法律", "权利"]
        search_results = {}
        
        for query in test_queries:
            try:
                # 文本搜索测试
                text_count = collection.count_documents({"$text": {"$search": query}})
                # 内容搜索测试  
                content_count = collection.count_documents({"content": {"$regex": query}})
                
                search_results[query] = {
                    "text_search": text_count,
                    "content_search": content_count
                }
                
                print(f"   '{query}': 文本搜索{text_count}条, 内容搜索{content_count}条")
                
                if text_count == 0 and content_count == 0:
                    health_report["issues"].append(f"搜索无结果：{query}")
                    
            except Exception as e:
                health_report["issues"].append(f"搜索错误 {query}: {str(e)}")
                print(f"   ❌ 搜索'{query}'失败: {str(e)}")
        
        health_report["statistics"]["search_results"] = search_results
        
        # 4. 性能检查
        print("\n⚡ 性能检查:")
        start_time = time.time()
        sample_results = list(collection.find({}).limit(100))
        query_time = (time.time() - start_time) * 1000
        
        print(f"   查询100条记录耗时: {query_time:.1f}ms")
        
        if query_time > 1000:  # 超过1秒
            health_report["issues"].append(f"查询性能慢：{query_time:.1f}ms")
            health_report["status"] = "warning"
        
        health_report["statistics"]["query_performance_ms"] = query_time
        
        # 5. 数据质量检查
        print("\n📋 数据质量检查:")
        
        # 检查空字段
        empty_content_count = collection.count_documents({"content": {"$in": ["", None]}})
        empty_keywords_count = collection.count_documents({"keywords": {"$in": [[], None]}})
        
        print(f"   空内容条文: {empty_content_count}条")
        print(f"   无关键词条文: {empty_keywords_count}条")
        
        if empty_content_count > 0:
            health_report["issues"].append(f"存在{empty_content_count}条空内容")
            
        health_report["statistics"]["empty_content"] = empty_content_count
        health_report["statistics"]["empty_keywords"] = empty_keywords_count
        
        # 6. 生成报告
        print("\n📄 健康检查报告:")
        if health_report["status"] == "healthy":
            print("   ✅ 数据库状态健康")
        elif health_report["status"] == "warning":
            print("   ⚠️ 数据库存在警告")
            for issue in health_report["issues"]:
                print(f"      - {issue}")
        else:
            print("   ❌ 数据库存在错误")
            for issue in health_report["issues"]:
                print(f"      - {issue}")
        
        # 保存报告
        report_file = f"health_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(health_report, f, ensure_ascii=False, indent=2, default=str)
        
        print(f"\n📁 报告已保存: {report_file}")
        
        client.close()
        return health_report["status"] == "healthy"
        
    except Exception as e:
        print(f"❌ 健康检查失败: {str(e)}")
        health_report["status"] = "error"
        health_report["issues"].append(f"检查失败: {str(e)}")
        return False

if __name__ == "__main__":
    health_check()
